<template>
  <div class="h-full flex flex-col bg-gray-50">
    <!-- 顶部标题栏 -->
    <div class="bg-white border-b border-gray-200 px-5 py-4 flex-shrink-0">
      <div class="flex items-center justify-between">
        <h2 class="m-0 text-gray-800 text-lg font-medium">设置</h2>
        <!-- 自动保存提示 -->
        <div v-if="autoSaveStatus" class="flex items-center gap-2 text-xs">
          <i :class="autoSaveStatus === 'saving' ? 'el-icon-loading' : 'el-icon-success'"
             :style="{ color: autoSaveStatus === 'saving' ? '#409EFF' : '#67C23A' }"></i>
          <span :style="{ color: autoSaveStatus === 'saving' ? '#409EFF' : '#67C23A' }">
            {{ autoSaveStatus === 'saving' ? '保存中...' : '已保存' }}
          </span>
        </div>
      </div>
    </div>

    <!-- 设置内容区 -->
    <div class="flex-1 overflow-y-auto p-6">
      <div class="max-w-3xl mx-auto">
        <!-- 变量加载设置 -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
          <div class="flex items-start justify-between mb-4">
            <div>
              <h3 class="text-base font-medium text-gray-800 m-0 flex items-center">
                <i class="el-icon-setting text-primary-500 mr-2"></i>
                变量加载深度
              </h3>
              <p class="text-sm text-gray-500 mt-2">
                配置调试时变量树的最大加载深度。此配置同时影响<span class="font-medium text-gray-700">局部变量</span>和<span class="font-medium text-gray-700">Watch表达式</span>。深度越大，加载的嵌套层级越多，但可能影响性能。
              </p>
            </div>
            <el-button size="mini" @click="resetToDefaults">
              <i class="el-icon-refresh-left mr-1"></i>
              重置
            </el-button>
          </div>

          <!-- 局部变量深度滑块 -->
          <div class="mb-5">
            <div class="flex items-center justify-between mb-3">
              <label class="text-sm font-medium text-gray-700">
                当前深度
              </label>
              <div class="flex items-center gap-2">
                <span class="text-2xl font-bold text-primary-500">{{ localVariableDepth }}</span>
                <span class="text-xs text-gray-500">层</span>
              </div>
            </div>
            <el-slider
              v-model="localVariableDepth"
              :min="1"
              :max="10"
              :marks="depthMarks"
              show-stops
              @change="handleDepthChange"
            ></el-slider>
          </div>

          <!-- 性能提示 -->
          <div class="space-y-3">
            <!-- 推荐提示 -->
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-3">
              <div class="flex items-start gap-2">
                <i class="el-icon-info text-blue-500 mt-0.5"></i>
                <div class="flex-1">
                  <p class="text-xs text-blue-800">
                    <span class="font-medium">推荐值: 3-5 层</span> - 平衡性能与可见性
                  </p>
                  <p class="text-xs text-blue-700 mt-1">
                    预计超时时间: <span class="font-semibold">{{ 5 + localVariableDepth * 2 }} 秒</span>
                  </p>
                </div>
              </div>
            </div>

            <!-- 警告提示 -->
            <div v-if="localVariableDepth > 7" class="bg-orange-50 border border-orange-200 rounded-lg p-3">
              <div class="flex items-start gap-2">
                <i class="el-icon-warning text-orange-500 mt-0.5"></i>
                <div class="flex-1">
                  <p class="text-xs text-orange-800 font-medium">
                    深度较高可能影响性能
                  </p>
                  <ul class="text-xs text-orange-700 mt-1 space-y-1 ml-4">
                    <li>• 复杂结构可能导致加载超时</li>
                    <li>• 断点命中时响应变慢</li>
                    <li>• 建议优先简化数据结构</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 轮询策略设置 -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
          <div class="flex items-start justify-between mb-4">
            <div>
              <h3 class="text-base font-medium text-gray-800 m-0 flex items-center">
                <i class="el-icon-time text-primary-500 mr-2"></i>
                状态轮询策略
              </h3>
              <p class="text-sm text-gray-500 mt-2">
                配置调试器状态检测的轮询间隔。较短的间隔响应更快，但会消耗更多 CPU 资源。
              </p>
            </div>
            <el-button size="mini" @click="resetPollingToDefault">
              <i class="el-icon-refresh-left mr-1"></i>
              重置
            </el-button>
          </div>

          <!-- 轮询间隔滑块 -->
          <div class="mb-5">
            <div class="flex items-center justify-between mb-3">
              <label class="text-sm font-medium text-gray-700">
                轮询间隔
              </label>
              <div class="flex items-center gap-2">
                <span class="text-2xl font-bold text-primary-500">{{ pollingInterval }}</span>
                <span class="text-xs text-gray-500">毫秒</span>
              </div>
            </div>
            <el-slider
              v-model="pollingInterval"
              :min="50"
              :max="1000"
              :step="50"
              :marks="pollingMarks"
              show-stops
              @change="handlePollingChange"
            ></el-slider>
          </div>

          <!-- 性能提示 -->
          <div class="space-y-3">
            <!-- 推荐提示 -->
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-3">
              <div class="flex items-start gap-2">
                <i class="el-icon-info text-blue-500 mt-0.5"></i>
                <div class="flex-1">
                  <p class="text-xs text-blue-800">
                    <span class="font-medium">推荐值: 100-200ms</span> - 平衡响应速度与资源消耗
                  </p>
                  <p class="text-xs text-blue-700 mt-1">
                    当前设置: <span class="font-semibold">{{ getPollingDescription() }}</span>
                  </p>
                </div>
              </div>
            </div>

            <!-- 警告提示 -->
            <div v-if="pollingInterval < 100" class="bg-orange-50 border border-orange-200 rounded-lg p-3">
              <div class="flex items-start gap-2">
                <i class="el-icon-warning text-orange-500 mt-0.5"></i>
                <div class="flex-1">
                  <p class="text-xs text-orange-800 font-medium">
                    轮询间隔过短可能影响性能
                  </p>
                  <ul class="text-xs text-orange-700 mt-1 space-y-1 ml-4">
                    <li>• CPU 使用率升高</li>
                    <li>• 电池续航降低（笔记本）</li>
                    <li>• 可能影响调试程序性能</li>
                  </ul>
                </div>
              </div>
            </div>

            <!-- 高延迟提示 -->
            <div v-if="pollingInterval > 500" class="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
              <div class="flex items-start gap-2">
                <i class="el-icon-warning text-yellow-600 mt-0.5"></i>
                <div class="flex-1">
                  <p class="text-xs text-yellow-800 font-medium">
                    轮询间隔较长会降低响应速度
                  </p>
                  <ul class="text-xs text-yellow-700 mt-1 space-y-1 ml-4">
                    <li>• 断点命中检测延迟增加</li>
                    <li>• 状态更新不够实时</li>
                    <li>• 建议在低性能设备上使用</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import debuggerApi from '@/api/debugger'

export default {
  name: 'SettingsView',
  data() {
    return {
      localVariableDepth: 3,  // 默认值
      pollingInterval: 100,    // 轮询间隔（毫秒），默认 100ms
      autoSaveStatus: null,    // 自动保存状态: null | 'saving' | 'saved'
      autoSaveTimer: null,     // 自动保存定时器
      depthMarks: {
        1: '1',
        3: '3',
        5: '5',
        7: '7',
        10: '10'
      },
      pollingMarks: {
        50: '50',
        100: '100',
        200: '200',
        500: '500',
        1000: '1000'
      }
    }
  },
  async mounted() {
    await this.loadSettings()
  },
  beforeDestroy() {
    // 清理定时器
    if (this.autoSaveTimer) {
      clearTimeout(this.autoSaveTimer)
    }
  },
  methods: {
    // 加载设置
    async loadSettings() {
      try {
        const result = await debuggerApi.loadSettings()
        if (result.success && result.settings) {
          this.localVariableDepth = result.settings.localVariableDepth || 3
          this.pollingInterval = result.settings.pollingInterval || 100
        }
      } catch (error) {
        console.error('[SettingsView] 加载设置失败:', error)
        this.$message.error('加载设置失败: ' + error.message)
      }
    },

    // 自动保存设置
    async autoSaveSettings() {
      try {
        this.autoSaveStatus = 'saving'

        const settings = {
          localVariableDepth: this.localVariableDepth,
          globalVariableDepth: 1,  // 全局变量固定为1
          pollingInterval: this.pollingInterval
        }

        const result = await debuggerApi.saveSettings(settings)

        if (result.success) {
          this.autoSaveStatus = 'saved'

          // 2秒后隐藏保存提示
          setTimeout(() => {
            this.autoSaveStatus = null
          }, 2000)

          // 发出事件通知设置已更新
          this.$emit('settings-updated', settings)
        } else {
          throw new Error(result.message || '保存失败')
        }
      } catch (error) {
        console.error('[SettingsView] 自动保存失败:', error)
        this.autoSaveStatus = null
        this.$message.error('保存设置失败: ' + error.message)
      }
    },

    // 深度改变时自动保存
    handleDepthChange(value) {
      // 清除之前的定时器
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer)
      }

      // 延迟500ms保存，避免滑动时频繁保存
      this.autoSaveTimer = setTimeout(() => {
        this.autoSaveSettings()
      }, 500)
    },

    // 恢复默认值
    resetToDefaults() {
      this.$confirm('确定要恢复默认设置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.localVariableDepth = 3
        this.pollingInterval = 100
        this.autoSaveSettings()
        this.$message.success('已恢复默认值')
      }).catch(() => {
        // 用户取消
      })
    },

    // 轮询间隔改变时自动保存
    handlePollingChange(value) {
      // 清除之前的定时器
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer)
      }

      // 延迟500ms保存，避免滑动时频繁保存
      this.autoSaveTimer = setTimeout(() => {
        this.autoSaveSettings()
      }, 500)
    },

    // 恢复轮询设置默认值
    resetPollingToDefault() {
      this.$confirm('确定要恢复轮询设置的默认值吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.pollingInterval = 100
        this.autoSaveSettings()
        this.$message.success('已恢复默认值')
      }).catch(() => {
        // 用户取消
      })
    },

    // 获取轮询间隔描述
    getPollingDescription() {
      if (this.pollingInterval <= 50) {
        return '极快响应（高CPU消耗）'
      } else if (this.pollingInterval <= 100) {
        return '快速响应（推荐）'
      } else if (this.pollingInterval <= 200) {
        return '正常响应（平衡）'
      } else if (this.pollingInterval <= 500) {
        return '较慢响应（省资源）'
      } else {
        return '慢速响应（低性能设备）'
      }
    }
  }
}
</script>

<style scoped>
/* 使用 Tailwind CSS 和全局样式 */
</style>
